<?php

namespace Rjyst\ClickLearn\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;

class InstallCommand extends Command
{
    protected $signature = 'click-learn:install';
    protected $description = 'Install Click Learn package';

    public function handle()
    {
        $this->info('🚀 开始安装 Click Learn 扩展包...');

        // 1. 发布并检查迁移文件
        $this->publishMigrations();

        // 2. 发布模型文件
        $this->publishModels();

        // 3. 发布管理后台文件
        $this->publishAdminFiles();

        // 4. 发布 Seeders
        $this->publishSeeders();

        // 5. 添加路由
        $this->addRoute();

        $this->info('🎉 Click Learn 扩展包安装完成！');
        $this->showNextSteps();
    }

    protected function publishMigrations()
    {
        $this->call('vendor:publish', ['--tag' => 'click-learn-migrations']);

        // 检查表是否存在，不存在则运行迁移
        if (!Schema::hasTable('click_learns')) {
            $this->info('click_learns 表不存在，正在创建...');
            $this->runSpecificMigration('2025_09_09_054709_create_click_learns_table.php');
        } else {
            $this->info('✅ click_learns 表已存在');
        }

        if (!Schema::hasTable('click_learn_spells')) {
            $this->info('click_learn_spells 表不存在，正在创建...');
            $this->runSpecificMigration('2025_09_09_054724_create_click_learn_spells_table.php');
        } else {
            $this->info('✅ click_learn_spells 表已存在');
        }
    }

    protected function runSpecificMigration($filename)
    {
        try {
            Artisan::call('migrate', ['--path' => 'database/migrations/' . $filename]);
            $this->info("✅ {$filename} 迁移完成");
        } catch (\Exception $e) {
            $this->error("迁移失败: " . $e->getMessage());
        }
    }

    protected function publishModels()
    {
        $this->call('vendor:publish', ['--tag' => 'click-learn-models']);

        // 检查模型是否存在
        $clickLearnModel = app_path('Models/Data/ClickLearn.php');
        $clickLearnSpellModel = app_path('Models/Data/ClickLearnSpell.php');

        if (File::exists($clickLearnModel)) {
            $this->info('✅ ClickLearn 模型已存在，跳过');
        } else {
            $this->info('✅ ClickLearn 模型创建完成');
        }

        if (File::exists($clickLearnSpellModel)) {
            $this->info('✅ ClickLearnSpell 模型已存在，跳过');
        } else {
            $this->info('✅ ClickLearnSpell 模型创建完成');
        }
    }

    protected function publishAdminFiles()
    {
        // 发布控制器
        $this->call('vendor:publish', ['--tag' => 'click-learn-controllers']);

        // 发布仓库
        $this->call('vendor:publish', ['--tag' => 'click-learn-repositories']);

        // 发布渲染器
        $this->call('vendor:publish', ['--tag' => 'click-learn-renderable']);

        // 检查管理后台文件是否存在
        $files = [
            'ClickLearnController' => app_path('Admin/Controllers/Data/ClickLearnController.php'),
            'ClickLearnRepository' => app_path('Admin/Repositories/Data/ClickLearn.php'),
            'SpellOptionData' => app_path('Admin/Renderable/Data/SpellOptionData.php'),
        ];

        foreach ($files as $name => $path) {
            if (File::exists($path)) {
                $this->info("✅ {$name} 已存在，跳过");
            } else {
                $this->info("✅ {$name} 创建完成");
            }
        }
    }

    protected function publishSeeders()
    {
        $this->call('vendor:publish', ['--tag' => 'click-learn-seeders']);

        $seeders = [
            'ClickLearnDataSeeder.php' => database_path('seeders/ClickLearnDataSeeder.php'),
            'ClickLearnMenuSeeder.php' => database_path('seeders/ClickLearnMenuSeeder.php'),
        ];

        foreach ($seeders as $name => $path) {
            if (File::exists($path)) {
                $this->info("✅ {$name} 已存在，跳过");
            } else {
                $this->info("✅ {$name} 创建完成");
            }
        }
    }

    protected function addRoute()
    {
        $routeFile = app_path('Admin/routes.php');
        $routeLine = "    \$router->resource('clickLearn', 'Data\\ClickLearnController');";

        if (!File::exists($routeFile)) {
            $this->warn('⚠️  Admin routes.php 文件不存在，请手动添加路由');
            return;
        }

        $content = File::get($routeFile);

        // 检查路由是否已存在
        if (strpos($content, "clickLearn") !== false) {
            $this->info('✅ 路由已存在');
            return;
        }

        // 查找最后一个 $router-> 行的位置
        $lines = explode("\n", $content);
        $lastRouterLineIndex = -1;
        $closingBraceIndex = -1;

        for ($i = count($lines) - 1; $i >= 0; $i--) {
            $line = trim($lines[$i]);

            // 查找闭合的大括号和分号 });
            if ($line === '});' && $closingBraceIndex === -1) {
                $closingBraceIndex = $i;
                continue;
            }

            // 在找到 }); 之后，查找最后一个 $router-> 行
            if ($closingBraceIndex !== -1 && strpos($line, '$router->') !== false) {
                $lastRouterLineIndex = $i;
                break;
            }
        }

        if ($lastRouterLineIndex !== -1) {
            // 在最后一个路由行后添加新路由
            array_splice($lines, $lastRouterLineIndex + 1, 0, $routeLine);
            $newContent = implode("\n", $lines);

            File::put($routeFile, $newContent);
            $this->info('✅ 路由添加完成');
        } else {
            $this->warn('⚠️  无法自动添加路由，请手动添加：');
            $this->line($routeLine);
        }
    }


    protected function showNextSteps()
    {
        $this->line('');
        $this->line('<fg=yellow>接下来你可以：</>');
        $this->line('1. 运行 <fg=green>php artisan db:seed --class=ClickLearnDataSeeder</> 导入数据');
        $this->line('2. 运行 <fg=green>php artisan db:seed --class=ClickLearnMenuSeeder</> 创建菜单');
        $this->line('3. 访问管理后台查看内容管理功能');
    }
}
